##
## Initial : 2020-01-07
##

output_version <- '2021-01-07'

# Salehyan, Idean, Cullen S. Hendrix, Jesse Hamner, Christina Case, 
# Christopher Linebarger, Emily Stull, and Jennifer Williams. 
# "Social conflict in Africa: A new database." International Interactions 
# 38, no. 4 (2012): 503-511.

#Go to https://www.strausscenter.org/ccaps-research-areas/social-conflict/database/.
url <- 'https://www.strausscenter.org/wp-content/uploads/SCAD2018Africa_Final.csv.zip'

destfile <- file.path(wkdir,'local','tab_data',basename(url))
xfun::dir_create(dirname(destfile))

# Download the file
httr::GET(url, write_disk(destfile, overwrite = TRUE))

# Unzip the downloaded file
unzip(destfile, exdir = 'SCAD2018Africa')

# List the files extracted to check
list.files('SCAD2018Africa')

# List files in the unzipped folder to find the CSV file
scad_csv_file <- list.files('SCAD2018Africa', full.names = TRUE, pattern = "\\.csv$")

# Read the CSV file using fread
scad.all.dt <- fread(scad_csv_file,blank.lines.skip=TRUE)

# subset lake chad countries
lkcctr <- c('Cameroon','Chad','Niger','Nigeria')
scad.dt <- subset(scad.all.dt,countryname %in% lkcctr)

# convert to points
scad_sf = st_as_sf(scad.dt, coords = c("longitude", "latitude"), 
                 crs = 4326, agr = "constant")

# ntl_adm0_x_01d
ntl.zones <- read_sf(dsn=paste0(wkdir,'/local/gis_data/003_boundaries/fishnet'),layer='fishnet_lake_chad_ntl_adm0_x_d01')
ntl.zones <- subset(ntl.zones,select=c(OBJECTID,GID_0))

setwd(wkdir)

# join points to objectid
scad_objectid_sf <- st_join(scad_sf,ntl.zones,join=st_nearest_feature)
#scad_objectid_sf <- st_nn(scad_sf,ntl.zones, k = 1, returnDist = T)

# output for stata labels
save.dta13(as.data.frame(st_drop_geometry(scad_objectid_sf)), 
           paste0(wkdir,"/proc_data/SCAD",output_version,".dta"))